﻿using System;
using System.Data.SQLite;
using System.IO;
using Labthink.PCSoft.UniversalHost4.Model.Setting;
using Labthink.PCSoft.UniversalHost4.Utility;
using NLog;

namespace SystemSettings
{
    public class CustomInfoHelper
    {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();

        public static CustomInfo Get()
        {
            CustomInfo info = null;
            if (HasTable())
            {
                var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(ConfigAndSettings.UnitDb));
                con.Open();
                try
                {
                    var cmd = con.CreateCommand();
                    var reader = SqliteHelper.ExecuteReader(cmd, "SELECT * FROM CustomInfo", null);
                    if (reader.Read())
                    {
                        info = new CustomInfo
                        {
                            CustName = reader["CustName"] + "",
                            CustLogo = reader["CustLogo"] + "",
                            CustThumb = reader["CustThumb"] + ""
                        };
                    }
                    reader.Close();
                }
                catch (Exception)
                {
                }

            }
            if (info != null)
            {
                if (!string.IsNullOrEmpty(info.CustLogo))
                {
                    foreach (var file in Directory.GetFiles(Path.Combine(ConfigAndSettings.CustomPath, "Logo")))
                    {
                        if (!file.Contains(info.CustLogo))
                        {
                            try
                            {
                                File.Delete(file);
                            }
                            catch (Exception)
                            {

                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(info.CustThumb))
                {
                    foreach (var file in Directory.GetFiles(Path.Combine(ConfigAndSettings.CustomPath, "Thumb")))
                    {
                        if (!file.Contains(info.CustThumb))
                        {
                            try
                            {
                                File.Delete(file);
                            }
                            catch (Exception)
                            {

                            }
                        }

                    }
                }
            }
            return info;

        }

        public static int Set(CustomInfo info)
        {
            if (!HasTable()) CreateTable();
            using (var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(ConfigAndSettings.UnitDb)))
            {
                con.Open();
                var tran = con.BeginTransaction();
                try
                {

                    SqliteHelper.ExecuteNonQuery(tran, "DELETE FROM CustomInfo");
                    var r = SqliteHelper.ExecuteNonQuery(tran,
                        "INSERT INTO CustomInfo (CustName,CustLogo,CustThumb) VALUES (@CustName,@CustLogo,@CustThumb)",
                        info.CustName, info.CustLogo, info.CustThumb);
                    tran.Commit();
                    return r;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    return -1;
                }
                finally
                {
                    con.Close();
                }
            }
        }

        public static int SaveLogo(string filePath, out string nf)
        {
            var dir = Path.Combine(ConfigAndSettings.CustomPath, "Logo");
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            var lf = Path.Combine(dir, Path.GetFileName(filePath));
            try
            {
                File.Move(filePath, lf);
                nf = lf.Replace(ConfigAndSettings.RootPath, "");
                return 1;
            }
            catch (Exception e)
            {
                Log.Error("保存Logo文件出错");
                Log.Error(e);
                nf = string.Empty;
                return -1;
            }
        }

        public static int SaveThumb(string filePath, out string nf)
        {
            var dir = Path.Combine(ConfigAndSettings.CustomPath, "Thumb");
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            var lf = Path.Combine(dir, Path.GetFileName(filePath));
            try
            {
                File.Move(filePath, lf);
                nf = lf.Replace(ConfigAndSettings.RootPath, "");
                return 1;
            }
            catch (Exception e)
            {
                Log.Error("保存Thumb文件出错");
                Log.Error(e);
                nf = string.Empty;
                return -1;
            }
        }

        public static string GetLogo(string file)
        {
            return ConfigAndSettings.RootPath + file;
        }

        public static string GetThumb(string file)
        {
            return ConfigAndSettings.RootPath + file;
        }

        private static bool HasTable()
        {
            var sql = "SELECT COUNT(1) FROM sqlite_master where type='table' and name='CustomInfo'";
            var o = SqliteHelper.ExecuteScalar(ConfigAndSettings.UnitDb, sql, null);
            if (o == null) return false;
            return o.ToInt32() > 0;
        }

        private static void CreateTable()
        {
            var sql = "CREATE TABLE [CustomInfo] ([CustName] VARCHAR(1000), [CustLogo] TEXT, [CustThumb] TEXT)";
            SqliteHelper.ExecuteNonQuery(ConfigAndSettings.UnitDb, sql, null);
        }
    }
}
